package test.my.com.myapplicationtest.banner_view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import test.my.com.myapplicationtest.R;

/**
 * Created by Cooper on 2016/5/5.
 */
public class BannerView extends FrameLayout implements ViewPager.OnPageChangeListener{

    private ViewPager mViewPager;
    private ViewPagerAdapter mAdapter;
    private LinearLayout mIndicatorLayout;
    private Builder mBuilder;
    private Context mContext;

    public boolean isHasTimer = false;

    private int mIndex=0;

    public int delay_time=3000;//默认3秒

    private Timer mTimer = new Timer();

    private Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int size = mBuilder.getImageUrls().size();
            mViewPager.setCurrentItem((mIndex % size));

        }
    };

    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            mIndex++;
            mHandler.sendEmptyMessage(0);

        }
    };

    public BannerView(Context context) {
        super(context);
        init(context);
    }

    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        mContext = context;
        mViewPager = new ViewPager(context);
        mAdapter = new ViewPagerAdapter();
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOnPageChangeListener(this);
        mIndicatorLayout = new LinearLayout(context);
        FrameLayout.LayoutParams params = new LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        params.bottomMargin = 10;
        addView(mViewPager, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.MATCH_PARENT);
        addView(mIndicatorLayout, params);
    }

    public void setBuilder(Builder builder){
        mBuilder = builder;
    }

    public void execute() {
        mAdapter.clear();
        mIndicatorLayout.removeAllViews();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);
        params.rightMargin = 10;
        for (final String imageUrl : mBuilder.getImageUrls()) {
            final ImageView imageView = new ImageView(mViewPager.getContext());
            mAdapter.setShowView(imageView);
            mAdapter.notifyDataSetChanged();

            ImageView indicator = new ImageView(mViewPager.getContext());
            indicator.setBackgroundResource(mBuilder.getIndicationConversionPic()[0]);
            mIndicatorLayout.addView(indicator, params);

            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext,"show",Toast.LENGTH_SHORT).show();
                }
            });

            final int screenWidth = imageView.getContext().getResources().getDisplayMetrics().widthPixels;
            final int screenHeight = imageView.getContext().getResources().getDisplayMetrics().heightPixels;
            DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565).build();
            ImageLoader.getInstance().displayImage(imageUrl, imageView, defaultOptions, new ImageLoadingListener(){
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    imageView.setBackgroundResource(R.drawable.banner);
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    int height = Math.round(bitmap.getHeight() * screenWidth / bitmap.getWidth());//根据显示宽度，计算图片实际显示高度
                    imageView.setImageBitmap(bitmap);
                    imageView.setTag(new int[]{screenWidth, height});
                    ViewPager.LayoutParams params = (ViewPager.LayoutParams) imageView.getLayoutParams();
                    if (params == null) {
                        params = new ViewPager.LayoutParams();
                    }
                    params.width = screenWidth;
                    params.height = height;
                    imageView.setLayoutParams(params);
                    if (mAdapter.getDatas().indexOf(imageView) == 0) {
                        FrameLayout.LayoutParams params1 = (FrameLayout.LayoutParams) mViewPager.getLayoutParams();
                        params1.width = screenWidth;
                        params1.height = height;
                        mViewPager.setLayoutParams(params1);
                        mIndicatorLayout.getChildAt(0).setBackgroundResource(mBuilder.getIndicationConversionPic()[1]);
                    }

                    if (mAdapter.getDatas().indexOf(imageView) == mAdapter.getDatas().size() - 1) {
                        mIndicatorLayout.setVisibility(VISIBLE);
                    }
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }

            });
        }
        mIndicatorLayout.setVisibility(GONE);

        if(isHasTimer){
            startTimer();
        }


    }

    public void startTimer(){
        mTimer.schedule(timerTask,delay_time,delay_time);
    }

    public void cancelTimer(){
        mTimer.cancel();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mIndex=position;
        int[] wh = (int[]) mAdapter.getDatas().get(position).getTag();
        if (wh != null) {
            FrameLayout.LayoutParams params1 = (FrameLayout.LayoutParams) mViewPager.getLayoutParams();
            params1.width = wh[0];
            params1.height = wh[1];
            mViewPager.setLayoutParams(params1);
        }
        for (int k = 0; k < mIndicatorLayout.getChildCount(); k++) {
            mIndicatorLayout.getChildAt(k).setBackgroundResource(mBuilder.getIndicationConversionPic()[0]);
        }
        mIndicatorLayout.getChildAt(position).setBackgroundResource(mBuilder.getIndicationConversionPic()[1]);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    public static class Builder {
        List<String> imageUrls;
        int[] indicationConversionPic;
        String tag;

        public String getTag() {
            return tag;
        }

        public Builder setTag(String tag) {
            this.tag = tag;
            return this;
        }

        public List<String> getImageUrls() {
            return imageUrls;
        }

        public Builder setImageUrls(List<String> imageUrls) {
            this.imageUrls = imageUrls;
            return this;
        }

        public int[] getIndicationConversionPic() {
            return indicationConversionPic;
        }

        public Builder setIndicationConversionPic(int[] indicationConversionPic) {
            this.indicationConversionPic = indicationConversionPic;
            return this;
        }
    }

    class ViewPagerAdapter extends PagerAdapter{

        private List<View> list;
        private LayoutParams params;

        public ViewPagerAdapter() {
            list = new ArrayList<>();
            params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        }

        public void setShowView(List<? extends View> list) {
            this.list.addAll(list);
        }

        public void setShowView(View view) {
            this.list.add(view);
        }

        public List<View> getDatas() {
            return list;
        }

        public void clear() {
            list.clear();
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            if (arg1 < list.size()) {
                ((ViewPager) arg0).removeView(list.get(arg1));
            }
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(list.get(arg1), params);
            return list.get(arg1);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }


        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }

}
